﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.Entity;
using System.Linq;
using System.Text;
using CommonHelp;
using Core.Unity;
using DbHelp;
using Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Services { 
    /// <summary>
    /// 水雨情
    /// </summary>
    public class SYQInfoService : Core.Unity.IInfoService {
        private EventHandler<ReceivedDataEventArgs> _ReceivedDataEvents;
        private List<SYQInfo> _DataList;

        public event EventHandler<ReceivedDataEventArgs> AfterQueryData {
            add {
                _ReceivedDataEvents += value;
            }
            remove {
                _ReceivedDataEvents -= value;
            }
        }

        public void OnModelCreating(ref DbModelBuilder modelBuilder) {
            modelBuilder.Entity<SYQInfo>().ToTable("WEBDATA_SYQ");
        }

        public void QueryData() {
            string url = ConfigurationManager.AppSettings["QuerySYQUrl"].ToString();
            HttpHelper http = new HttpHelper(url);
            http.GetAsync(AfterGetData);
        }

        private void AfterGetData(string responseString) {
            JArray nodes = JArray.Parse(responseString);
            List<SYQInfo> infos = new List<SYQInfo>();
            for (int i = 0; i < nodes.Count; i++) {
                JToken jToken = nodes[i];
                SYQInfo info = JsonConvert.DeserializeObject<SYQInfo>(jToken.ToString());
                info.IDX = Guid.NewGuid().ToString();
                infos.Add(info);
            }

            _DataList = infos;
              
            if (_ReceivedDataEvents != null) {
                _ReceivedDataEvents(this, new ReceivedDataEventArgs(infos));
            }
        }

        public void SaveData(object data) {
            using (WebDataContext db = new WebDataContext()) {
                List<SYQInfo> list = data as List<SYQInfo>;
                DbSet<SYQInfo> infos = db.Set<SYQInfo>();
                foreach (var item in list) {
                    if (infos.Any(a => a.ID == item.ID && a.POI_CODE == item.POI_CODE && a.TM == item.TM)) {
                        continue;
                    }

                    infos.Add(item);
                }
                db.SaveChanges();
            }
        }
    }
}
